import json
import os
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
import logging

logger = logging.getLogger(os.environ.get('APP_NAME'))


class AliYunClound(object):
    def __init__(self):
        self.config = open_api_models.Config(
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )

    def client(self):
        self.config.endpoint = f'dysmsapi.aliyuncs.com'
        return Dysmsapi20170525Client(self.config)

    async def sms(self,sign_name, template_code, mobile, template_param) -> None:
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name=sign_name,
            template_code=template_code,
            phone_numbers=mobile,
            template_param=json.dumps(template_param)
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            response = await self.client().send_sms_with_options_async(send_sms_request, runtime)
            return response.body
        except Exception as error:
            logger.error(f"短信发送异常 ，{error}")











# if __name__ == '__main__':
#     # aliyun = AliYunClound(key='LTAI5t6mVXkAmGyoqp8WxTjN', secret='dsCRhXa52eQXT23MkzuLDvUVhZEc4i')
#     # mobile = '13729029559'
#     # template_param = {'code': '55555'}
#     # sign_name = '阿里云短信测试'
#     # template_code = 'SMS_154950909'
#     # result = AliYunClound.sms(mobile=mobile, template_param=template_param, sign_name=sign_name, template_code=template_code)
#     # print(result)
#
#     sms_client = AliYunClound()
#     sms_client.sms(
#         sign_name='阿里云短信测试',
#         template_code='SMS_154950909',
#         mobile='15239513161',
#         template_param={'code': '1234'}
#     )
